package com.xzbd.gef.controller;

import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPolicy;

import com.xzbd.core.gef.Node;
import com.xzbd.gef.model.RootNode;
import com.xzbd.gef.policy.AppEditLayoutPolicy;
import com.xzbd.gef.view.RootNodeFigure;
import com.xzbd.listeners.PropListener;

public class RootNodePart extends AppAbstractEditPart{

	@Override
	protected IFigure createFigure() {
		IFigure figure = new RootNodeFigure();
		return figure;
	}

	@Override
	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.LAYOUT_ROLE, new AppEditLayoutPolicy());
	}

	@Override
	protected List<Node> getModelChildren() {
		if(Objects.isNull(getModel())) {
			return new ArrayList<>();
		}
		return ((RootNode) getModel()).getChildren();
	}

	@Override
	public void refreshVisuals() {
		RootNodeFigure figure = (RootNodeFigure) getFigure();
		RootNode model = (RootNode) getModel();
		if(Objects.isNull(model)) {
			model = new RootNode();
		}
		
		figure.setName(model.getName());
		figure.setAddress(model.getAddress());
		figure.setVersion(model.getVersion());
		figure.setDate(model.getDate());
		figure.setAuthor(model.getAuthor());
	}

	private void refreshSize() {
		RootNodeFigure figure = (RootNodeFigure) getFigure();
		Integer maxWidth = 0;
		Integer maxHeight = 0;
		List<Node> childs = ((Node) this.getModel()).getChildren();
		for (Node child : childs) {
			Rectangle childLayout = child.getLayout();
			if (childLayout.x + childLayout.width >= maxWidth)
				maxWidth = childLayout.x + childLayout.width;
			if (childLayout.y + childLayout.height >= maxHeight)
				maxHeight = childLayout.y + childLayout.height;
		}
		figure.setLayout(new Rectangle(0, 0, maxWidth + 500, maxHeight + 500));
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals(PropListener.PROPERTY_LAYOUT))
			refreshVisuals();
		if (evt.getPropertyName().equals(PropListener.PROPERTY_ADD)) {
			refreshChildren();
			refreshSize();
		}
		if (evt.getPropertyName().equals(PropListener.PROPERTY_REMOVE)) {
			refreshChildren();
			refreshSize();
		}
		if (evt.getPropertyName().equals(PropListener.PROPERTY_RENAME))
			refreshVisuals();
		if (evt.getPropertyName().equals(PropListener.PROPERTY_VERSION))
			refreshVisuals();
		if (evt.getPropertyName().equals(PropListener.PROPERTY_DATE))
			refreshVisuals();
		if (evt.getPropertyName().equals(PropListener.PROPERTY_AUTHOR))
			refreshVisuals();
	}
}
